package com.qf.dao.impl;

import com.qf.dao.OrderDao;
import com.qf.model.Goods;
import com.qf.model.Order;
import com.qf.util.JDBCUtil;
import org.apache.commons.dbutils.QueryRunner;
import org.apache.commons.dbutils.handlers.BeanHandler;
import org.apache.commons.dbutils.handlers.BeanListHandler;

import java.sql.*;
import java.util.List;

public class OrderDaoImpl implements OrderDao {
    QueryRunner qr=new QueryRunner();
    @Override
    public int insertOrderByOrder(Order o) {

        Connection con=null;
        int a=0;
        try{
            con= JDBCUtil.getCon();
            String sql="insert into Torder (onum,omoney,ostatus,otime,uid,aid) values(?,?,?,?,?,?)";
           // a = qr.update(con, sql,o.getOnum(),o.getOmoney(),o.getOstatus(),o.getOtime(),o.getUid(),o.getAid());
            PreparedStatement pre = con.prepareStatement(sql, Statement.RETURN_GENERATED_KEYS);
            pre.setString(1,o.getOnum());
            pre.setBigDecimal(2,o.getOmoney());
            pre.setInt(3,o.getOstatus());
            pre.setTimestamp(4,new Timestamp(o.getOtime().getTime()));
            pre.setInt(5,o.getUid());
            pre.setInt(6,o.getAid());
            pre.executeUpdate();
            //拿到自动生成的主键id
            ResultSet rs = pre.getGeneratedKeys();
            while(rs.next()){
                int nextId = rs.getInt(1);
                o.setId(nextId);
                System.out.println();
            }

            //想办法得到刚刚插入时自动生成的oid的值
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            JDBCUtil.colseCon(con);
        }

        return a;

    }

    @Override
    public List<Order> selectOrdersByUid(int uid) {
        Connection con=null;
        List<Order> list=null;
        try {
            con= JDBCUtil.getCon();
            //默认只查询上架的商品
            String sql="select * from Torder where uid=?";

            list = qr.query(con,sql,new BeanListHandler<Order>(Order.class),uid);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            JDBCUtil.colseCon(con);
        }
        return list;
    }

    @Override
    public Order selectOrdersByOid(int oid) {

        Connection con=null;
        Order order=null;
        try {
            con= JDBCUtil.getCon();
            //默认只查询上架的商品
            String sql="select * from Torder where id=?";

            order = qr.query(con,sql,new BeanHandler<Order>(Order.class),oid);
        }catch (Exception e){
            e.printStackTrace();
        }finally {
            JDBCUtil.colseCon(con);
        }
        return order;



    }
}
